package com.wn.common.listener;

import com.rabbitmq.client.Channel;
import com.wn.model.vo.CartVo;
import com.wn.service.CartService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

/**
 * 清空购物车监听器
 */
@Component
@RabbitListener(queues = "clear.cart.queue")  //监听队列
@Slf4j
public class ClearCartListener {
    @Autowired
    private CartService cartService;
    /**
     * 清理购物车
     */
    @SneakyThrows
    @RabbitHandler  //指定方法
    public void clearCart(CartVo cartVo, Message message, Channel channel,
                          @Header(AmqpHeaders.DELIVERY_TAG) Long deliveryTag) {
        log.info("收到清空购物车消息:{}", cartVo);
        try {
            //执行清理操作
            cartService.clearCart(cartVo.getUserId());
            //手动确认消息
            channel.basicAck(deliveryTag, false);
            log.info("清空购物车成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.info("清空购物车失败");
            //拒绝消息，重新入队
            Boolean redelivered = message.getMessageProperties().getRedelivered();
            //获取重投标记
            if (redelivered) {
                log.error("清空购物车消息重试超过次数，拒绝消息");
                channel.basicReject(deliveryTag, false);
            } else {
                log.error("清空购物车消息重试一次");
                channel.basicNack(deliveryTag, false, true);
            }
        }
    }
}